package sso;

import Algorithm.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

public class DecryptTest {
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// 默认的加密算法


    public static String decrypt(String content, String password) {

        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
            byte[] result = cipher.doFinal(Base64.decode(content));
            return new String(result, "utf-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 生成加密秘钥
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) {
        if (null == key || key.length() == 0) {
            throw new NullPointerException("key not is null");
        }
        SecretKeySpec key2 = null;
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
            kgen.init(128);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            key2 = new SecretKeySpec(enCodeFormat, KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return key2;
    }

    public static void main(String[] args) {
        //  加密是用了钥匙，AESUtil.encrypt(cookieValue, "anxl_sso_aess_pub_key");
        String cookieValue = "GKfaCY2NkoOCp/on3XF982J3dNvc26fY1NiT1+75exQerAN3DTd+U+o9iBikjOyVz8AazttKU/vK5NsRRWWftYpCD8NLLtsS37Y1tvD4aYGJpg1VtdsTwu9zLM5GgOpIJbsNqI7QQFyaftGGaxGJHbVJLfUqkoROGDcyLGvmOu4=\n";

        // 解密
        // 解密必须要钥匙！！！，这个钥匙就是“anxl_sso_aess_pub_key”,除非黑客或者其他人拿到钥匙，才能解密出来
        // 1.下面的可以解密出来
        String v1 = AESUtil.decrypt(cookieValue, "anxl_sso_aess_pub_key");
        System.out.println("v1="+v1);

        // 2.下面的不可以解密出来
        String v2  = AESUtil.decrypt(cookieValue, "suibiande");
        System.out.println("v2="+v2);
    }
}
